var fs = require('fs');
var os = require('os');
var express = require('express');
var mysql = require('mysql');
var utils = require('../utils');
var router = express.Router();

var multiparty = require('multiparty');

var database = require('../database.config');
var connection = mysql.createConnection(database);
connection.connect();

function getIpHost() {
  var IPv4 = [];
  var interfaces = os.networkInterfaces();
  for (var devName in interfaces) {
    var iface = interfaces[devName];
    for (var i = 0; i < iface.length; i++) {
      var alias = iface[i];
      if (alias.family === 'IPv4' && alias.address !== '127.0.0.1' && !alias.internal) {
        IPv4.push(alias.address);
      }
    }
  }
  return IPv4;
}

router.post('/upload', function (req, res, next) {
  //生成multiparty对象，并配置上传目标路径
  var form = new multiparty.Form({ uploadDir: './public/images/' });

  form.parse(req, function (err, fields, files) {
    if (err) {
      console.log('文件长传错误: ' + err);
    } else {
      var inputFile = files.files[0];
      var uploadedPath = inputFile.path;
      var dstPath = './public/images/' + inputFile.originalFilename;
      //重命名为真实文件名
      fs.rename(uploadedPath, dstPath, function (err) {
        if (err) {
          console.log('文件重命名为真实文件名错误: ' + err);
        } else {
          var result = {
            base: 'http://' + req.host + ':' + global.port,
            url: '/images/' + inputFile.originalFilename
          }
          res.send(utils.sendData(result));
        }
      });
    }
  });
});

module.exports = router;